#!/bin/bash
# sh ./tssh_branch_and_upload_result.sh

# 当前【shell脚本】的工作目录
# $PWD代表获取当前路径，当cd后，$PWD也会跟着更新到新的cd路径。这个和在终端操作是一样的道理的
CurrentDIR_Script_Absolute="$( cd "$( dirname "$0" )" && pwd )"
#echo "CurrentDIR_Script_Absolute=${CurrentDIR_Script_Absolute}"
#CommonFun_HomeDir_Absolute2=${CurrentDIR_Script_Absolute}/..
CommonFun_HomeDir_Absolute2=${CurrentDIR_Script_Absolute%/*} # 使用此方法可以避免路径上有..
CommonFun_HomeDir_Absolute=${CommonFun_HomeDir_Absolute2%/*}

qscript_path_get_filepath="${CommonFun_HomeDir_Absolute}/qscript_path_get.sh"
qbase_update_json_file_singleString_script_path="$(sh ${qscript_path_get_filepath} qbase update_json_file_singleString)"
qbase_notification2wechat_path="$(sh ${qscript_path_get_filepath} qbase notification2wechat)"


# 之前测试分支使用的数据的目录
BRANCH_TEST_DIR="${CommonFun_HomeDir_Absolute}/brances_info/brances_info_log/test"

Package_Environment_FILE_PATH="${BRANCH_TEST_DIR}/data/test_data_env_info.json"


My_TEST_ROBOT_URL="https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=925776da-1ff4-417a-922a-d5ced384050e"

function updateEnvKeyValue() {
    EnvKey=$1
    EnvValue=$2
    sh ${qbase_update_json_file_singleString_script_path} -jsonF "${Package_Environment_FILE_PATH}" -k "${EnvKey}" -v "${EnvValue}"
    if [ $? != 0 ]; then
        exit 1
    fi
}
function updateEnvKeyFileValue() {
    if [ ! -f "$2" ]; then
        echo "❌Error:在$FUNCNAME方法中,发现[$2]文件不存在，请先检查！"
        exit
    fi
    updateEnvKeyValue "$1" "$2"
}

# 测试发送通知
function test_notification() {
    SEND_NOTIFICATION_TEXT=$1
    # 将结果发送通知
    TEST_ROBOT_URL=${My_TEST_ROBOT_URL}
    sh ${qbase_notification2wechat_path} -robot "${TEST_ROBOT_URL}" -content "${SEND_NOTIFICATION_TEXT}" -msgtype "markdown" --enableMD "true"
}


function test_upload_result_log_sh() {
    echo "----------------------------------------------------------------------------7最终信息的脚本upload_result_log_sh"
    # 设置前提条件
    TEST_DATA_RESULT_FILE_PATH="${CurrentDIR_Script_Absolute}/data/tsdata_branch_result.json"
    updateEnvKeyValue "platform_type" "Android"
    updateEnvKeyValue "package_default_env" "product"
    updateEnvKeyValue "package_default_target" "formal"
    updateEnvKeyFileValue "branchsResultJsonFile" "${TEST_DATA_RESULT_FILE_PATH}"
    updateEnvKeyFileValue "uploadSupplementJsonFile" "${CommonFun_HomeDir_Absolute}/upload/upload_result_log.json"
    
    # 正式执行
    #echo "正在引入函数文件(用于获取最后的打包通知消息)：《source ${CommonFun_HomeDir_Absolute}/upload/upload_result_log.sh》"
    source ${CommonFun_HomeDir_Absolute}/upload/upload_result_log.sh 
    getUpdateLog_all -envInfoF "${Package_Environment_FILE_PATH}" -comScriptHomeDir "${CommonFun_HomeDir_Absolute}" --update-log-use-type "Notification"
    if [ $? != 0 ]; then
        echo "❌Error:执行 getUpdateLog_all 的时候出错"
    fi
    LongLog=${PackageUploadResultText}
    echo "LongLog=${LongLog}"

    # 将结果发送通知
    # TEST_ROBOT_URL=${My_TEST_ROBOT_URL}
    # sh ${qbase_notification2wechat_path} -robot "${TEST_ROBOT_URL}" -content "${LongLog}" -msgtype "markdown" --enableMD "true"
    test_notification "${LongLog}"

    # echo "\n"
    # echo "----------------------------------------处理后文件最后的完整内容"
    UPDATE_INFO_SAVE_FILE_PATH=$(cat ${PRODUCT_APP_Environment_FILE_PATH} | jq -r '.branchsResultJsonFile')
    # cat ${UPDATE_INFO_SAVE_FILE_PATH} | jq '.'

    REQUEST_FOR_LOG_TYPE_ARRAY=("Notification" "Pgyer")
    REQUEST_FOR_LOG_TYPE_COUNT=${#REQUEST_FOR_LOG_TYPE_ARRAY[*]}
    for((i=0;i<${REQUEST_FOR_LOG_TYPE_COUNT};i++));
    do
        REQUEST_FOR_LOG_TYPE_STRING=${REQUEST_FOR_LOG_TYPE_ARRAY[i]}
        # echo "----------------------------.branch_info_result.${REQUEST_FOR_LOG_TYPE_STRING}----------------------------"
        # cat ${UPDATE_INFO_SAVE_FILE_PATH} | jq ".branch_info_result.${REQUEST_FOR_LOG_TYPE_STRING}" | jq '.'
        echo "----------------------------.branch_info_result.${REQUEST_FOR_LOG_TYPE_STRING}.all.intercept----------------------------"
        cat ${UPDATE_INFO_SAVE_FILE_PATH} | jq ".branch_info_result.${REQUEST_FOR_LOG_TYPE_STRING}.all.intercept" | jq '.'
    done
    
    
    # echo "{}" > ${UPDATE_INFO_SAVE_FILE_PATH} #清空文件内容,但清空成{}
    echo "\n\n"
}



# 测试实际项目结果的通知
function test_PRODUCT_APP_Environment() {
    echo "----------------------------------------------------------------------------8实际项目结果的获取+通知"
    # 1、设置前提条件
    PRODUCT_APP_Environment_FILE_PATH=${CommonFun_HomeDir_Absolute%/*}/example_packing_info/app_info.json
    TEST_DATA_RESULT_FILE_PATH="${CurrentDIR_Script_Absolute}/data/tsdata_branch_result.json"
    function updateProductEnvKeyValue() {
        EnvKey=$1
        EnvValue=$2
        sh ${qbase_update_json_file_singleString_script_path} -jsonF "${PRODUCT_APP_Environment_FILE_PATH}" -k "${EnvKey}" -v "${EnvValue}"
        if [ $? != 0 ]; then
            exit 1
        fi
    }
    function updateProductEnvKeyFileValue() {
        if [ ! -f "$2" ]; then
            echo "❌Error:在$FUNCNAME方法中,发现[$2]文件不存在，请先检查！"
            exit 1
        fi
        updateProductEnvKeyValue "$1" "$2"
    }


    function getAllPackingInfo() {
        updateProductEnvKeyFileValue "historyVersionJsonFile" "${CommonFun_HomeDir_Absolute%/*}/example_packing_info/app_history_version.json"
        sh ${CommonFun_HomeDir_Absolute%/*}/example_packing_info/all_packing_info.sh -resultSaveToJsonF "${TEST_DATA_RESULT_FILE_PATH}"
        if [ $? != 0 ]; then
            echo "❌Error:测试执行 test_PRODUCT_APP_Environment 的时候出错"
            return 1
        fi
        echo "✅✅✅✅✅恭喜:您的分支信息获取完毕，已存放到文件中，详见: ${TEST_DATA_RESULT_FILE_PATH} ✅✅✅✅✅"
    
        updateProductEnvKeyValue "platform_type" "Android"
        updateProductEnvKeyValue "package_default_env" "product"
        updateProductEnvKeyValue "package_default_target" "formal"
        # updateProductEnvKeyFileValue "branchsResultJsonFile" "${TEST_DATA_RESULT_FILE_PATH}"
        updateProductEnvKeyFileValue "uploadSupplementJsonFile" "${CommonFun_HomeDir_Absolute}/upload/upload_result_log.json"
   
        Package_Url_Result_KEY="package_url_result"
        Package_Url_Result_VALUE="{
            \"package_local_url\": \"~/xxx/Product/dempApp/iOS_product_inner_dev_publish_out_1.0.1(14241813).ipa\",
            \"package_local_backup_dir\": \"~/xxx/Product/backup/iOS_product_inner_dev_publish_out_1.0.1(14241813).ipa\",
            \"package_cos_url\": \"https://images.xihuanwu.com/mcms/download/app/iOS_product_inner_dev_publish_out_1.0.1(14241813).ipa\"
        }"
        sh ${CommonFun_HomeDir_Absolute}/update_json_file.sh -f "${PRODUCT_APP_Environment_FILE_PATH}" -k "${Package_Url_Result_KEY}" -v "${Package_Url_Result_VALUE}" -skipVCheck "true"
        if [ $? != 0 ]; then
            exit
        fi
    }
    getAllPackingInfo
    if [ $? != 0 ]; then
        exit 1
    fi

    # 2、正式执行
    echo "正在引入函数文件(用于获取最后的打包通知消息)：《source ${CommonFun_HomeDir_Absolute}/upload/upload_result_log.sh》"
    source ${CommonFun_HomeDir_Absolute}/upload/upload_result_log.sh 
    getUpdateLog_all -envInfoF "${PRODUCT_APP_Environment_FILE_PATH}" -comScriptHomeDir "${CommonFun_HomeDir_Absolute}" --update-log-use-type "Notification"
    if [ $? != 0 ]; then
        echo "❌Error:执行 getUpdateLog_all 的时候出错"
        return 1
    fi
    LongLog=${PackageUploadResultText}
    # echo "LongLog=${LongLog}"


    # 注意📢2：因为上面使用jquery取值的时候没使用 jq -r 属性，所以 fileValueWithoutEscape 会保留前后的双引号。
    # 所以①：设置 json 的时候，不要再重复添加前后的双引号了。
    # 所以②：更新 json 值到文件 file 的时候，直接使用【没使用 jq -r 属性取出来的值】，不要去转义后，再添加。
    # BRANCH_OUTLINES_LOG_JSON="{\"data2\": \"${LongLog}\"}"
    # # TEST_JSON_FILE_PATH=${CurrentDIR_Script_Absolute}/tsdata_update_text_variable.json
    # sh "${CommonFun_HomeDir_Absolute}/update_json_file.sh" -f "${UPDATE_INFO_SAVE_FILE_PATH}" -k "test_result" -v "${BRANCH_OUTLINES_LOG_JSON}" --skip-value-check "true"
    # 注意📢3：使用jquery取值的时候，不要使用 jq -r 属性
    UPDATE_INFO_SAVE_FILE_PATH=$(cat ${PRODUCT_APP_Environment_FILE_PATH} | jq -r '.branchsResultJsonFile')
    # cat ${UPDATE_INFO_SAVE_FILE_PATH}  | jq '.branch_info_result.current' | jq '.Notification_full'
    branchLogType="Notification" # Notification / Pgyer
    echo "-------------《cat ${UPDATE_INFO_SAVE_FILE_PATH} | jq \".branch_info_result.${branchLogType}.all.slice\" | jq '.'》-------------"
    echo "-------------.branch_info_result.${branchLogType}.all.slice-------------"
    cat ${UPDATE_INFO_SAVE_FILE_PATH} | jq ".branch_info_result.${branchLogType}.all.slice" | jq '.'
    echo "-------------.branch_info_result.${branchLogType}.header-------------"
    cat ${UPDATE_INFO_SAVE_FILE_PATH} | jq ".branch_info_result.${branchLogType}.header" | jq '.'
    echo "-------------.branch_info_result.${branchLogType}.bottom-------------"
    cat ${UPDATE_INFO_SAVE_FILE_PATH} | jq ".branch_info_result.${branchLogType}.bottom" | jq '.'
    echo "-------------.branch_info_result.${branchLogType}.all.intercept-------------"
    cat ${UPDATE_INFO_SAVE_FILE_PATH} | jq ".branch_info_result.${branchLogType}.all.intercept" | jq '.'
    
    # 将结果发送通知
    AllInterceptArrayKey="branch_info_result.${branchLogType}.all.intercept"
    TEST_ROBOT_CONENT_COUNT=$(cat ${UPDATE_INFO_SAVE_FILE_PATH} | jq ".${AllInterceptArrayKey}" | jq ".|length")
    # echo "=============TEST_ROBOT_CONENT_COUNT=${TEST_ROBOT_CONENT_COUNT}"
    if [ ${TEST_ROBOT_CONENT_COUNT} -eq 0 ]; then
        echo "友情提醒💡💡💡：没有找到可发送的测试数据"
        return 1
    fi

    for (( i = 0; i < ${TEST_ROBOT_CONENT_COUNT}; i++ )); do
        TEST_ROBOT_CONENT=$(cat ${UPDATE_INFO_SAVE_FILE_PATH} | jq ".${AllInterceptArrayKey}" | jq ".[${i}]")

        TEST_ROBOT_URL=${My_TEST_ROBOT_URL}
        
        # sh ${qbase_notification2wechat_path} -robot "${TEST_ROBOT_URL}" -content "${TEST_ROBOT_CONENT}" -msgtype "markdown" --enableMD "true"
        test_notification "${TEST_ROBOT_CONENT}"
        continue

        MentionedListJsonStrings="[\"@all\"]"
        MessageTYPE="markdown" # text \ markdown
        wechatDJson="{
            \"msgtype\": \"${MessageTYPE}\",
            \"${MessageTYPE}\": {
                \"content\": ${TEST_ROBOT_CONENT}
            }
        }"
        echo "---------------------wechatDJson=\n${wechatDJson}"


        responseResult=$(\
        curl $TEST_ROBOT_URL \
           -H "Content-Type: application/json" \
           -d "${wechatDJson}"
        )

        if [ $? = 0 ]   # 上个命令的退出状态，或函数的返回值。
        then
            echo "responseResult=$responseResult"
            responseResultCode=$(echo ${responseResult} | jq  '.errcode') # mac上安装brew后，执行brew install jq安装jq
            if [ $responseResultCode = 0 ];then
                echo "-------- ✅通知成功 --------"
            else
                responseErrorMessage=$(echo ${responseResult} | jq  '.errmsg')
                echo "-------- ❌通知失败responseErrorMessage=${responseErrorMessage} --------"
                return 1
            fi
        else
            echo "-------- ❌通知失败：执行通知命令失败 --------"
            return 1
        fi
    done
    

    echo "\n\n"
}


# test_upload_result_log_sh
test_PRODUCT_APP_Environment

